package com.growthsee.rider.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.PostConstruct;
import java.util.Collection;
import java.util.Map;

/**
 * 获取容器中对象的工具类
 *
 * @author chensiyou
 * <p>
 * Created on 2020/09/4.
 */
@Component
public class ApplicationContexts implements ApplicationContextAware {
    private ApplicationContext _applicationContext;

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this._applicationContext = applicationContext;
    }

    @PostConstruct
    public void init() {
        ApplicationContexts.applicationContext = this._applicationContext;
    }

    public static <T> T getBean(Class<T> requiredType) throws BeansException {
        return ApplicationContexts.applicationContext.getBean(requiredType);
    }

    public static <T> Collection<T> getBeansOfType(Class<T> requiredType) throws BeansException {
        Map<String, T> beansOfType = ApplicationContexts.applicationContext.getBeansOfType(requiredType);
        return beansOfType.values();
    }

    public static ServletRequestAttributes getServletRequestAttributes() {
        return (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    }
}
